package com.spark.sort.bubble;

/**
 * @Author sc
 * @DATE 2024/6/6 1:20
 * @Description: 冒泡排序实现
 * @Version 1.0
 */
public class BubbleMain {
    public static void main(String[] args) {

        Integer[] arr = {1,3,4,2,5,1,2,4,55,77,65,22,21313,131535,3131,45464,132535,22223,41,-1};
        for (Integer integer : arr) {
            System.out.print(integer + " ");
        }
        System.out.println("\n===============冒泡排序开始=================");
        bubbleSort(arr);
        for (Integer integer : arr) {
            System.out.print(integer + " ");
        }
        System.out.println("\n===============优化冒泡排序开始=================");
        optBubbleSort(arr);
        for (Integer integer : arr) {
            System.out.print(integer + " ");
        }
    }

    public static void bubbleSort(Integer[] arr){
        long beg = System.currentTimeMillis();
        for (int i = 0; i < arr.length - 1; i++) { //冒泡几次
            // 冒泡的步骤
            for(int j = 0; j < arr.length - 1- i;j++){
                if(arr[j] > arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("使用时间：" + (end - beg));
    }

    public static void optBubbleSort(Integer[] arr){
        long beg = System.currentTimeMillis();
        for (int i = 0; i < arr.length - 1; i++) { //冒泡几次
            boolean IndexFlag = false;
            // 冒泡的步骤
            for(int j = 0; j < arr.length - 1- i;j++){
                if(arr[j] > arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    IndexFlag = true;
                }
                if (!IndexFlag){
                    break;
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("使用时间：" + (end - beg));
    }
}
